import pygame
import random
import os

# 初始化Pygame
pygame.init()

# 游戏窗口设置
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 720
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("羊了个羊")

# 颜色定义
BG_COLOR = (255, 255, 255)

# 卡片尺寸和间距
CARD_WIDTH = 55
CARD_HEIGHT = 70
# 增加卡片堆的间隔
SPACING = 20

# 游戏区域布局
GRID_ROWS = 3
GRID_COLS = 3
grid_width = GRID_COLS * (CARD_WIDTH + SPACING) - SPACING
GRID_LEFT = (SCREEN_WIDTH - grid_width) // 2
GRID_TOP = 100

# 槽位区域设置
SLOT_ROWS = 1
SLOT_COLS = 7  # 最多存放7个卡片
slot_width = SLOT_COLS * (CARD_WIDTH + 5) - 5
SLOT_LEFT = (SCREEN_WIDTH - slot_width) // 2
SLOT_TOP = SCREEN_HEIGHT - CARD_HEIGHT - 50
SLOT_HEIGHT = CARD_HEIGHT + 20

# 道具图标尺寸
ITEM_ICON_WIDTH = 50
ITEM_ICON_HEIGHT = 50

# 加载动态背景图片
try:
    image_folder = os.path.join(os.path.dirname(__file__), "image")
    background_files = ["back.png", "back1.png"]
    background_images = []
    for file in background_files:
        background_path = os.path.join(image_folder, file)
        if os.path.exists(background_path):
            img = pygame.image.load(background_path)
            img = pygame.transform.scale(img, (SCREEN_WIDTH, SCREEN_HEIGHT))
            background_images.append(img)
        else:
            print(f"背景图片 {background_path} 不存在")

    if len(background_images) != 2:
        raise Exception("没有找到足够的背景图片")
    print("动态背景图像加载成功")
    current_background_index = 0
    background_change_interval = 10  # 每10帧切换一次背景
    frame_count = 0
except Exception as e:
    print(f"动态背景图像加载失败: {e}")
    background_images = None

# 加载槽位背景图像
try:
    slot_bg_path = os.path.join(image_folder, "back2.png")
    slot_bg_img = pygame.image.load(slot_bg_path)
    slot_bg_img = pygame.transform.scale(slot_bg_img, (slot_width + 20, SLOT_HEIGHT + 20))
    print("槽位背景图像加载成功")
except Exception as e:
    print(f"槽位背景图像加载失败: {e}")
    slot_bg_img = None

# 加载卡片图片
card_images = []
try:
    for i in range(5):
        if i == 0:
            tile_path = os.path.join(image_folder, "tile.png")
        else:
            tile_path = os.path.join(image_folder, f"tile{i}.png")

        if os.path.exists(tile_path):
            img = pygame.image.load(tile_path)
            img = pygame.transform.scale(img, (CARD_WIDTH, CARD_HEIGHT))
            card_images.append(img)
            print(f"卡片图片 {os.path.basename(tile_path)} 加载成功")
        else:
            print(f"卡片图片 {tile_path} 不存在")

    if not card_images:
        raise Exception("没有找到任何卡片图片")

except Exception as e:
    print(f"卡片图片加载失败: {e}")
    COLORS = [
        (255, 0, 0),  # 红
        (0, 255, 0),  # 绿
        (0, 0, 255),  # 蓝
        (255, 255, 0),  # 黄
        (128, 0, 128),  # 紫
    ]

# 加载道具图标
try:
    item_icon_path = os.path.join(image_folder, "item_icon.jpg")
    item_icon = pygame.image.load(item_icon_path)
    item_icon = pygame.transform.scale(item_icon, (ITEM_ICON_WIDTH, ITEM_ICON_HEIGHT))
except Exception as e:
    print(f"道具图标加载失败: {e}")
    item_icon = None

# 加载胜利图片
try:
    win_image_path = os.path.join(image_folder, "win.png")
    win_image = pygame.image.load(win_image_path)
    win_image = pygame.transform.scale(win_image, (SCREEN_WIDTH, SCREEN_HEIGHT))
    print("胜利图片加载成功")
except Exception as e:
    print(f"胜利图片加载失败: {e}")
    win_image = None

# 游戏状态
slots = []
score = 0
game_over = False
game_won = False
item_count = 1  # 初始附赠一个道具

def check_victory():
    """检查是否胜利"""
    for row in grid:
        for stack in row:
            if len(stack) > 0:
                return False
    return len(slots) == 0

# 初始化卡片堆
grid = []
for row in range(GRID_ROWS):
    grid_row = []
    for col in range(GRID_COLS):
        layers = random.randint(3, 5)
        max_card_type = len(card_images) - 1 if card_images else len(COLORS) - 1
        stack = [random.randint(0, max_card_type) for _ in range(layers)]
        stack += [stack[-1]] * (3 - layers % 3) if layers % 3 != 0 else []
        grid_row.append(stack)
    grid.append(grid_row)

# 主循环
clock = pygame.time.Clock()
running = True

while running:
    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN and not game_over:
            x, y = pygame.mouse.get_pos()
            # 计算槽位背景图片的位置
            slot_bg_x = SLOT_LEFT - 10
            slot_bg_y = SLOT_TOP - 10
            # 计算道具图标位置，使其位于槽位背景图片上方
            item_icon_x = slot_bg_x + slot_width - ITEM_ICON_WIDTH
            item_icon_y = slot_bg_y - ITEM_ICON_HEIGHT - 10
            item_icon_rect = pygame.Rect(item_icon_x, item_icon_y, ITEM_ICON_WIDTH, ITEM_ICON_HEIGHT)
            if item_icon_rect.collidepoint(x, y) and item_count > 0:
                slots = []
                item_count -= 1
            else:
                # 计算点击位置
                found = False
                for row in range(GRID_ROWS):
                    for col in range(GRID_COLS):
                        stack = grid[row][col]
                        for layer in range(len(stack)):
                            card_x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
                            card_y = GRID_TOP + row * (CARD_HEIGHT + SPACING) + layer * 10  # 每层卡片有一定的偏移
                            card_rect = pygame.Rect(card_x, card_y, CARD_WIDTH, CARD_HEIGHT)
                            if card_rect.collidepoint(x, y) and layer == len(stack) - 1:  # 只有最上层卡片可以点击
                                if len(slots) >= SLOT_COLS:
                                    game_over = True
                                    continue

                                card = stack.pop()
                                slots.append(card)

                                if len(slots) >= 3 and slots[-1] == slots[-2] == slots[-3]:
                                    del slots[-3:]
                                    score += 1
                                    # 检查分数是否达到3的倍数
                                    if score % 3 == 0:
                                        item_count += 1

                                if len(slots) >= SLOT_COLS:
                                    game_over = True

                                if check_victory():
                                    game_won = True
                                    game_over = True

                                found = True
                                break
                        if found:
                            break
                    if found:
                        break

    # 绘制界面
    if not game_won:
        if background_images:
            screen.blit(background_images[current_background_index], (0, 0))
            frame_count += 1
            if frame_count % background_change_interval == 0:
                current_background_index = (current_background_index + 1) % len(background_images)
        else:
            screen.fill(BG_COLOR)

        # 绘制卡片堆
        for row in range(GRID_ROWS):
            for col in range(GRID_COLS):
                stack = grid[row][col]
                for layer in range(len(stack)):
                    card_x = GRID_LEFT + col * (CARD_WIDTH + SPACING)
                    card_y = GRID_TOP + row * (CARD_HEIGHT + SPACING) + layer * 10  # 每层卡片有一定的偏移
                    card_type = stack[layer]
                    if card_images:
                        screen.blit(card_images[card_type], (card_x, card_y))
                    else:
                        pygame.draw.rect(screen, COLORS[card_type], (card_x, card_y, CARD_WIDTH, CARD_HEIGHT))

        # 绘制槽位背景
        if slot_bg_img:
            slot_bg_x = SLOT_LEFT - 10
            slot_bg_y = SLOT_TOP - 10
            screen.blit(slot_bg_img, (slot_bg_x, slot_bg_y))
        else:
            pygame.draw.rect(screen, (200, 200, 200),
                             (SLOT_LEFT - 5, SLOT_TOP - 5,
                              slot_width + 10, SLOT_HEIGHT + 10),
                             border_radius=10)

        # 绘制槽位中的卡片
        for i, card in enumerate(slots):
            x = SLOT_LEFT + i * (CARD_WIDTH + 5)
            if card_images:
                screen.blit(card_images[card], (x, SLOT_TOP))
            else:
                pygame.draw.rect(screen, COLORS[card], (x, SLOT_TOP, CARD_WIDTH, CARD_HEIGHT))

        # 绘制状态信息
        font = pygame.font.Font(None, 36)
        text = font.render(f"Score: {score}", True, (0, 0, 0))
        screen.blit(text, (20, 20))

        # 绘制槽位容量提示
        capacity_text = font.render(f"{len(slots)}/{SLOT_COLS}", True, (100, 100, 100))
        screen.blit(capacity_text, (SCREEN_WIDTH - 60, 20))

        # 绘制道具图标和数量
        if item_icon:
            slot_bg_x = SLOT_LEFT - 10
            slot_bg_y = SLOT_TOP - 10
            item_icon_x = slot_bg_x + slot_width - ITEM_ICON_WIDTH
            item_icon_y = slot_bg_y - ITEM_ICON_HEIGHT - 10
            screen.blit(item_icon, (item_icon_x, item_icon_y))
            item_count_text = font.render(f"{item_count}", True, (0, 0, 0))
            screen.blit(item_count_text, (item_icon_x + ITEM_ICON_WIDTH - 10, item_icon_y))
    else:
        if win_image:
            screen.blit(win_image, (0, 0))
        else:
            font = pygame.font.Font(None, 36)
            text = font.render("YOU WIN!", True, (0, 255, 0))
            screen.blit(text, (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20))

    if game_over and not game_won:
        font = pygame.font.Font(None, 36)
        text = font.render("GAME OVER!", True, (255, 0, 0))
        screen.blit(text, (SCREEN_WIDTH // 2 - 80, SCREEN_HEIGHT // 2 - 20))

    pygame.display.flip()
    clock.tick(30)

pygame.quit()